using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace DataStubGenerator.Views
{
    public class FileData
    {
        public DataTable GetTableBy(string sql)
        {           
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            DataTable table = db.ExecuteDataSet(cmd).Tables[0].Copy();
            table.TableName = FindTableName(sql);
            return table;
        }

        private string FindTableName(string sql)
        {
            int afterFromIndex = sql.ToLower().IndexOf("from") + "from".Length + 1;//1 is for the space
            string[] afterFromWords = sql.Substring(afterFromIndex).Split(' ');
            return afterFromWords[0];//first word after "from" is the table name 
        }
    }
}
